package com.mdinic.blogovi.front.common;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;

public abstract class AbstractFormFeedbackPanel<T> extends Panel {

    private static final String FORM = "form";

    private static final String FEEDBACK = "feedback";

    public static final String ID = "panel";

    private static final long serialVersionUID = -562342074406466893L;

    public AbstractFormFeedbackPanel(String id, T entity) {
        super(id);

        final Form<T> form = new Form<T>(FORM, new CompoundPropertyModel<T>(entity));

        add(form);
        add(new FeedbackPanel(FEEDBACK).setOutputMarkupId(true));
        addOkButton();
    }

    protected abstract void submit(T object);

    protected void addOkButton() {
        getForm().add(new OkButton("ok"));
    }

    protected FeedbackPanel getFeedbackPanel() {
        return (FeedbackPanel) get(FEEDBACK);
    }

    @SuppressWarnings("unchecked")
    protected Form<T> getForm() {
        return ((Form<T>) get(FORM));
    }

    private class OkButton extends Button {

        private static final long serialVersionUID = -6330000414783520406L;

        public OkButton(String id) {
            super(id);
        }

        @Override
        public void onSubmit() {
            submit(AbstractFormFeedbackPanel.this.getForm().getModelObject());
        }
    }

}
